package com.tct.smartRE.fwk.impl.dao;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.tct.smartRE.fwk.api.IBusinessObject;
import com.tct.smartRE.fwk.api.IQueryCondition;
import com.tct.smartRE.fwk.api.dao.ICommonDAO;

public class CommonDAO extends HibernateDaoSupport implements ICommonDAO {

	public void delete(IBusinessObject object) {
		getHibernateTemplate().delete(object);
	}

	public void delete(Integer id, Class<?> clazz) {
		IBusinessObject obj = load(id, clazz);
		delete(obj);
	}

	public Integer countAll(final Class<?> clazz) {
		return countByCondition(new QueryConditionTemplate() {
			@Override
			public String getQuery() {
				return "select count(*) from " + clazz.getSimpleName();
			}
		});
	}

	public Integer countByCondition(IQueryCondition queryCondition) {
		Query query = createQuery(queryCondition.getQuery());

		if(queryCondition.getParams() != null) {
			for (int i = 0; i < queryCondition.getParams().size(); i++) {
				query.setParameter(i, queryCondition.getParams().get(i));
			}
		}
		return (Integer) query.uniqueResult();
	}

	public List<IBusinessObject> findAll(final Class<?> clazz) {
		return findByCondition(new QueryConditionTemplate() {
			@Override
			public String getQuery() {
				return "from " + clazz.getSimpleName();
			}
		});
	}

	@SuppressWarnings("unchecked")
	public List<IBusinessObject> findByCondition(IQueryCondition queryCondition) {
		Query query = createQuery(queryCondition.getQuery());

		if(queryCondition.getParams() != null) {
			for (int i = 0; i < queryCondition.getParams().size(); i++) {
				query.setParameter(i, queryCondition.getParams().get(i));
			}
		}
		
		if(queryCondition.getFirstResult() == null) {
			query.setFirstResult(0);
		}else {
			query.setFirstResult(queryCondition.getFirstResult().intValue());
		}
		
		if (queryCondition.getMaxResult() != null && queryCondition.getMaxResult().intValue() > -1) {
			query.setMaxResults(queryCondition.getMaxResult().intValue());
		}
		
		List<IBusinessObject> lst = query.list();
		return lst;
	}

	Query createQuery(String queryString) {
		return getSession(false).createQuery(queryString);
	}

	public IBusinessObject load(Integer id, Class<?> clazz) {
		return (IBusinessObject) getHibernateTemplate().load(clazz, id);
	}

	public Integer save(IBusinessObject object) {
		Integer id = object.getId();
		setSystemInfo(object);
		if (object.getId() != null) {
			getHibernateTemplate().merge(object);
		} else {
			id = (Integer) getHibernateTemplate().save(object);
		}
		return id;
	}

	private void setSystemInfo(IBusinessObject obj) {
		obj.setCreatedDate(new Date());
		obj.setCreatedUser("");
		obj.setUpdatedUser("");
	}
}
